<template>
  <div class="statisticsChart">
    <div class="searchBox search-box-layout mb16">
      <Row :gutter="24">
        <Col span="4">
          <div>
            <p class="label">{{ $t("工站") }}</p>
            <div class="ipt">
              <Cascader
                clearable
                :data="orgList"
                v-model="searchParams.orgCode"
                :placeholder="`${$t('common.selectInfo')}`"
                change-on-select
              >
              </Cascader>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{ $t("问题类型") }}</p>
            <div class="ipt">
              <Select
                v-model="searchParams.issueType"
                clearable
                filterable
                :placeholder="`${$t('common.selectInfo')}`"
              >
                <Option
                  v-for="(item, index) of issueTypeList"
                  :value="item.name"
                  :key="index"
                  :label="item.name"></Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{ $t("原因代码") }}</p>
            <div class="ipt">
              <Select
                v-model="searchParams.reasonCode"
                clearable
                filterable
                :placeholder="`${$t('common.selectInfo')}`"
              >
                <Option
                  v-for="(item, index) of reasonList"
                  :value="item.reasonCode"
                  :key="index"
                  :label="item.reasonCode + '-' + item.reasonDesc">
                </Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{ $t("统计周期") }}</p>
            <div class="ipt">
              <Select
                v-model="searchParams.type"
                :placeholder="`${$t('common.selectInfo')}`"
              >
                <Option
                  v-for="(item, index) of typeList"
                  :value="item.id"
                  :key="index"
                  :label="item.name"
                  ></Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4" v-if="searchParams.type === 1">
          <div>
            <p class="label">{{ $t("日") }}</p>
            <div class="ipt">
                <a-range-picker :allowClear="false" v-model="timeList1" />
            </div>
          </div>
        </Col>
        <Col span="4" v-if="searchParams.type === 2">
          <div>
            <p class="label">{{ $t("周") }}</p>
            <div class="ipt">
                <a-week-picker :allowClear="false" v-model="timeList2" />
            </div>
          </div>
        </Col>
        <Col span="4" v-if="searchParams.type === 3">
          <div>
            <p class="label">{{ $t("月") }}</p>
            <div class="ipt">
                <a-range-picker
                  :allowClear="false"
                  format="YYYY-MM"
                  v-model="timeList3"
                  :mode="mode2"
                  @panelChange="handlePanelChange2"
                  @change="handleChange"
                />
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label hide-label">--</p>
            <div class="ipt">
              <Button class="search-btn" type="primary" @click="getList">{{
                $t("common.Query")
              }}</Button>
              <Button class="reset-btn" @click="resetSearch()"
                >{{ $t("common.reset") }}
              </Button>
            </div>
          </div>
        </Col>
      </Row>
    </div>
    <div class="list-layout mt16">
      <div class="echatone" id="workHour"></div>
    </div>
    <div class="list-layout mt16">
      <div class="echatone">
        <div class="echattwo" id="reasonRadio"></div>
        <div class="echatthree" id="trendsHour"></div>
      </div>
    </div>
  </div>
</template>

<script>
import recursion from "../../../util/recursion";
import { searchApi } from "@/api/andon/reasonCode/index.js";
import * as echarts from "echarts";
// import zh_CN from "ant-design-vue/lib/locale-provider/zh_CN";
import "moment/locale/zh-cn";
import { DatePicker} from 'ant-design-vue';
import moment from 'moment'
let myChart, myChart1, myChart2;
const {MonthPicker,WeekPicker,RangePicker } = DatePicker
export default {
  name: "statisticsChart",
  components: {
    // ADatePicker:DatePicker,
    AMonthPicker:MonthPicker,
    AWeekPicker:WeekPicker,
    ARangePicker:RangePicker
  },
  data() {
    return {
      // locale: window.localStorage.getItem("language") === "en_US" ? "" : zh_CN,
      typeList: [
        { id: 1, name: `${this.$t("日")}` },
        { id: 2, name: `${this.$t("周")}` },
        { id: 3, name: `${this.$t("月")}` },
      ],
      searchParams: {
        type: 1,
      },
      orgList: [],
      mode2: ['month', 'month'],
      timeList1: [this.$moment(new Date()),this.$moment(new Date())],
      timeList2: this.$moment(new Date()),
      timeList3: [this.$moment(new Date()),this.$moment(new Date())],
      issueTypeList: [
        { id: 1, name: '设备问题' },
        { id: 2, name: '质量问题' },
        { id: 3, name: '物料问题' },
        { id: 4, name: '工艺问题' },
        { id: 5, name: '人为问题' },
        { id: 6, name: '其他问题' }
      ],
      list: [],
      reasonList: [
        {
          reasonCode: '27_M1',
          reasonDesc: 'T4-1 等待物料'
        },
        {
          reasonCode: '27_P2',
          reasonDesc: 'T4-2 等待维修'
        },
        {
          reasonCode: '27_Q1',
          reasonDesc: 'T3-1 来料返工'
        },
        {
          reasonCode: '27_Q2',
          reasonDesc: 'T3-4 拒收返工'
        },
        {
          reasonCode: '27_Q3',
          reasonDesc: 'T3-2 过程返工'
        },
        {
          reasonCode: '27_O1',
          reasonDesc: 'T4-6 新员工效率损失'
        },
        {
          reasonCode: '27_P1',
          reasonDesc: 'T2-2 员工过程调整'
        },
        {
          reasonCode: '27_P4',
          reasonDesc: 'T4-3 订单异常'
        },
        {
          reasonCode: '27_O2',
          reasonDesc: 'T4-4 等待其他相关部门支持'
        },
        {
          reasonCode: '27_P3',
          reasonDesc: 'T4-5 MES 系统 1PA 系统'
        }
      ],
    };
  },
  beforeCreate(){
    if (localStorage.getItem('language') === 'zh_CN'){
      moment.locale('zh-cn');
    }
  },
  created() {},
  mounted() {
    this.getOrgList();
    this.getList();
  },
  methods: {
    handleChange(value) {
      this.timeList3 = value;
    },
    handlePanelChange2(value, mode) {
      this.timeList3 = value;
      this.mode2 = [mode[0] === 'date' ? 'month' : mode[0], mode[1] === 'date' ? 'month' : mode[1]];
    },
    resetSearch(){
        this.searchParams = {
          type: 1,
        }
        this.getList()
    },
    getOrgList() {
      this.axios({
        method: "get",
        url: "/basic/organization/findListByToken",
        params: {},
      }).then((res) => {
        if (res.code === 200) {
          const obj = {
            label: "name",
            value: "code",
            children: "children",
          };
          this.orgList = recursion.convertTree(res.data, obj);
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    workHourEchart(xAxisData, xAxisGroupData, seriesData, groupSeparates) {
      if (myChart != null && myChart != "" && myChart != undefined) {
        myChart.dispose(); //销毁
      }
      myChart = echarts.init(document.getElementById("workHour"));
      myChart.setOption({
        grid: {
          //图的边距
          top: "15%", //左边距
          left: "3%", //左边距
          right: "3%", //右边距
          bottom: "-5%", //下边距
          containLabel: true,
        },
        title: {
          text: this.$t("影响工时原因分析"),
        },
        tooltip: {},
        xAxis: [
          {
            position: "bottom",
            data: xAxisData,
            axisTick: {
              length: 0, // 刻度线的长度
            },
            axisLabel: {
              // rotate:-45,
              fontSize:12,
              // formatter:function(value)
              // {
              //     // debugger
              //     var ret = "";//拼接加\n返回的类目项
              //     var maxLength = 4 ;//每项显示文字个数
              //     var valLength = value.length;//X轴类目项的文字个数
              //     var rowN = Math.ceil(valLength / maxLength); //类目项需要换行的行数
              //     if (rowN >1 )//如果类目项的文字大于3,
              //     {
              //         for (var i =0 ; i < rowN; i++) {
              //             var temp = "";//每次截取的字符串
              //             var start = i * maxLength;//开始截取的位置
              //             var end = start + maxLength;//结束截取的位置
              //             //这里也可以加一个是否是最后一行的判断，但是不加也没有影响，那就不加吧
              //             temp = value.substring(start, end) + "\n";
              //             ret += temp; //凭借最终的字符串
              //         }
              //         return ret;
              //     }
              //     else {
              //         return value;
              //     }
              // }
              //margin: 10, // 标签到轴线的距离
            },
          },
          {
            position: "bottom",
            data: xAxisGroupData,
            axisTick: {
              length: 60,
              interval: function (index, value) {
                return groupSeparates[index]; // 根据标识分组的刻度线
              },
            },
            axisLabel: {
              color: "#000",
              fontSize: 16,
              margin: 50,
              interval: 0, // 显示所有标签
              rich: {
                offset: {
                  width: 0,
                },
              },
            },
          },
        ],
        yAxis: {
          type: "value",
          axisLabel: {
            formatter: "{value}H",
          },
        },
        series: [
          {
            type: "bar",
            barWidth: 20,
            data: seriesData,
          },
        ],
      });
      myChart.lastBandWidth = 0;
      // 监听渲染事件，只要bandWidth发生变化，重新设置标签偏移的值
      myChart.on("rendered", function () {
        let bandWidth =
          myChart._chartsViews[0].renderTask.context.outputData._layout
            .bandWidth;
        if (myChart.lastBandWidth != bandWidth) {
          myChart.lastBandWidth = bandWidth;
          // 延时执行否则echarts渲染异常
          setTimeout(() => {
            // 加上偏移后重新绘制
            let optionNew = { xAxis: [{}, {}] };
            // 增量更新偏移值
            optionNew.xAxis[1] = {
              axisLabel: { rich: { offset: { width: myChart.lastBandWidth } } },
            };
            //console.info(optionNew);
            myChart.setOption(optionNew);
          }, 0);
        }
      });
      window.addEventListener("resize", function () {
        myChart.resize(); //myChart指自己定义的echartsDom对象
      });
    },
    reasonRadioEchart(sum, arr) {
      if (myChart1 != null && myChart1 != "" && myChart1 != undefined) {
        myChart1.dispose(); //销毁
      }
      let title = this.$t("总影响工时")
      myChart1 = echarts.init(document.getElementById("reasonRadio"));
      myChart1.setOption({
        title: {
          text: this.$t("影响工时原因占比TOP5"),
        },
        // graphic: {
        //   type: "text",
        //   left: "24%",
        //   top: "45%",
        //   style: {
        //     text: this.$t("总影响工时")+"\n\n" + sum,
        //     textAlign: "center",
        //     fill: "#333",
        //     fontSize: 14,
        //     fontWeight: 700,
        //   },
        // },
        legend: {
          orient: "vertical", // 控制水平排列
          top: "center", // 调整位置
          right: "0%", // 距离右侧位置
          icon: "circle", // 修改小图标为圆形
          itemHeight: 12, // 修改圆形小图标的大小
          textStyle: {
            // 文字的样式
            fontSize: 24, // 可控制每个legend项的间距
            color: "#828282",
            rich: {
              // 通过富文本rich给每个项设置样式，下面的oneone、twotwo、threethree可以理解为"每一列"的样式
              oneone: {
                // 设置文字、数学、英语这一列的样式
                // width: 120,
                color: "#000000",
                fontSize: 12,
                fontWeight: "bolder",
              },
              twotwo: {
                // 设置10分、20分、30分这一列的样式
                // width: 40,
                color: "#333",
                fontSize: 12,
              },
              threethree: {
                // 设置百分比这一列的样式
                // width: 60,
                fontSize: 12,
              },
            },
          },
          formatter: (name) => {
            let total = 0; // 用于计算总数
            let target; // 遍历拿到数据
            for (let i = 0; i < arr.length; i++) {
              total += arr[i].value;
              if (arr[i].name == name) {
                target = arr[i].value;
              }
            }
            let v = ((target / total) * 100).toFixed(2);
            return `{oneone|${name}} {threethree|${v}%} {twotwo|${target}H}`;
            //     富文本第一列样式应用    富文本第二列样式应用      富文本第三列样式应用
          },
        },
        tooltip: {
          trigger: 'item'
        },
        series: [
          {
            // name: 'Access From',
            type: "pie",
            center: ["30%", "50%"],
            radius: ["50%", "70%"],
            avoidLabelOverlap: false,
            label: {
              normal:{
                show: true,
                position: "center",
                formatter:function(){
                    return title+"\n\n\n"+ sum+'H';
                },
                color: "#000000",
                fontSize: 12,
                fontWeight: "bolder",
              }
            },
            tooltip: {
              valueFormatter: function (value) {
                return value + 'H';
              }
            },
            labelLine: {
              show: false,
            },
            data: arr,
          },
        ],
      });
      window.addEventListener("resize", function () {
        myChart1.resize(); //myChart指自己定义的echartsDom对象
      });
    },
    trendsHourEchart(x,title,y) {
      if (myChart2 != null && myChart2 != "" && myChart2 != undefined) {
        myChart2.dispose(); //销毁
      }
      myChart2 = echarts.init(document.getElementById("trendsHour"));
      myChart2.setOption({
        title: {
          text: this.$t("影响工时类型分析"),
        },
        grid: {
          //图的边距
          top: "15%", //左边距
          left: "3%", //左边距
          right: "3%", //右边距
          bottom: "0%", //下边距
          containLabel: true,
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            crossStyle: {
              color: "#999",
            },
          },
        },
        legend: {
          data: title,
        },
        xAxis: [
          {
            type: "category",
            data: x,
            axisPointer: {
              type: "shadow",
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            // name: "Precipitation",
            axisLabel: {
              formatter: "{value}H",
            },
          },
        ],
        series: y,
      });
      window.addEventListener("resize", function () {
        myChart2.resize(); //myChart指自己定义的echartsDom对象
      });
    },
    getList() {
      let params = {};
      for (let key in this.searchParams) {
        if (this.searchParams[key]) {
          this.$set(params, key, this.searchParams[key]);
        }
      }
      params.orgCode = params.orgCode && params.orgCode.at(-1);
      if (params.type === 1) {
        params.startDate = this.$moment(this.timeList1[0]).format("YYYY-MM-DD");
        params.endDate = this.$moment(this.timeList1[1]).format("YYYY-MM-DD");
      }
      if (params.type === 2) {
        params.startDate = this.$moment(this.timeList2).format("YYYY-ww");
        params.endDate   = this.$moment(this.timeList2).format("YYYY-ww");
      }
      if (params.type === 3) {
        params.startDate = this.$moment(this.timeList3[0]).format("YYYY-MM");
        params.endDate = this.$moment(this.timeList3[1]).format("YYYY-MM");
      }
      this.axios({
        method: "post",
        url: "/dms/andonTask/andonAnalysis",
        data: params,
      }).then((res) => {
        if (res.code === 200) {
          let xAxisData = [];
          let seriesData = [];
          let xAxisGroupData = []; // 分组显示的标签（组内如果是偶数加上偏移{offset|}，如果是计数放正中间）
          let groupSeparates = []; // 分组分隔线
          let oneKey = Object.keys(res.data);
          let oneVal = Object.values(res.data);
          for (let item of oneVal) {
            for (let obj of Object.keys(item)) {
              xAxisData.push(obj);
            }
            for (let obj of Object.values(item)) {
              seriesData.push(obj);
            }
          }
          for (let i = 0; i < oneKey.length; i++) {
            let index = Math.trunc(Object.keys(oneVal[i]).length / 2);
            for (let o = 0; o < Object.keys(oneVal[i]).length; o++) {
              if (o == 0) {
                groupSeparates.push(true);
              } else {
                groupSeparates.push(false);
              }
              if (Object.keys(oneVal[i]).length % 2 === 0) {
                if (index - 1 === o) {
                  xAxisGroupData.push(`{offset|}${oneKey[i]}`);
                } else {
                  xAxisGroupData.push("");
                }
              } else {
                if (index === o) {
                  xAxisGroupData.push(oneKey[i]);
                } else {
                  xAxisGroupData.push("");
                }
              }
            }
          }
          this.workHourEchart(
            xAxisData,
            xAxisGroupData,
            seriesData,
            groupSeparates
          );
        }
      });
      this.axios({
        method: "post",
        url: "/dms/andonTask/andonReasonProp",
        data: params,
      }).then((res) => {
        if (res.code === 200) {
          let sum = 0;
          let arr = [];
          if (res.data && res.data.length > 0) {
            sum = res.data[0].sumWorkTime;
            for (let item of res.data) {
              arr.push({ name: item.reasonDesc, value: item.workTime });
            }
          }
          this.reasonRadioEchart(sum, arr);
        }
      });
      this.axios({
        method: "post",
        url: "/dms/andonTask/affectingWorkTime",
        data: params,
      }).then((res) => {
        if (res.code === 200) {
          let oneKey = Object.keys(res.data);
          let oneVal = Object.values(res.data);
          let xAxisData = []
          let seriesData = []
          for (let item of oneVal) {
            for (let obj of Object.keys(item)) {
              xAxisData.push(obj);
            }
            for (let obj of Object.values(item)) {
              seriesData.push(obj);
            }
          }
          const uni = [...new Set(xAxisData)]
          let y = []
          for(let i=0;i<uni.length;i++){
            let arr = []
            for(let j=0;j<xAxisData.length;j++){
              if(xAxisData[j]==uni[i]){
                arr.push(seriesData[j])
              }
            }
            y.push({name:uni[i],type: "bar",barWidth:'20',data:arr})
          }
          console.log(y)
          this.trendsHourEchart(oneKey,uni,y);
        }
      });
    },
  },
};
</script>
<style scoped lang="scss">
.statisticsChart {
  .list-layout {
    .echatone {
      width: 100%;
      height: 320px;
      display: flex;
      .echattwo {
        height: 100%;
        width: 40%;
      }
      .echatthree {
        height: 100%;
        width: 60%;
      }
    }
  }
}
</style>
